import json
from datetime import datetime

from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
from config import DB_URL
from news_json import news_table_structure

engine = create_engine(DB_URL)

def news_all():
    sql = text("SELECT * FROM news")
    try:
        with engine.connect() as conn:
            result = conn.execute(sql)
            rows = result.fetchall()  # 只调用一次fetchall()

            # 获取列名
            column_names = [column['name'] for column in news_table_structure['columns']]
            news_list = [dict(zip(column_names, row)) for row in rows]
            for news_item in news_list:
                for key, value in news_item.items():
                    if isinstance(value, datetime):
                        news_item[key] = value.isoformat()
            return news_list  # 直接返回列表而非JSON字符串

    except SQLAlchemyError as e:
        print(e)
        return None
